package com.ruoyi.purchase.service.impl;

import java.util.*;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.purchase.domain.PurchaseOrders;
import com.ruoyi.purchase.domain.PurchaseOrdersDetails;
import com.ruoyi.purchase.mapper.BoxCodesMapper;
import com.ruoyi.purchase.mapper.PurchaseOrdersMapper;
import com.ruoyi.purchase.vo.BoxCodesVO;
import com.ruoyi.purchase.vo.DeliveryItemVO;
import com.ruoyi.purchase.vo.DeliveryVO;
import com.ruoyi.purchase.vo.PurchaseOrderPageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.purchase.domain.DeliveryDetail;
import com.ruoyi.purchase.mapper.DeliveryMapper;
import com.ruoyi.purchase.domain.Delivery;
import com.ruoyi.purchase.service.IDeliveryService;

/**
 * 发货单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-26
 */
@Service
public class DeliveryServiceImpl implements IDeliveryService 
{
    @Autowired
    private DeliveryMapper deliveryMapper;

    @Autowired
    private BoxCodesMapper boxCodesMapper;

    @Autowired
    private PurchaseOrdersMapper purchaseOrdersMapper;


    @Override
    @Transactional
    public AjaxResult confirmDelivery(Long id) {
        try {
            // 1. 更新发货单状态为已发货
            Delivery delivery = deliveryMapper.selectDeliveryById(id);
            if (delivery == null) {
                return AjaxResult.error("发货单不存在");
            }
            if (delivery.getDeliveryStatus() == 1L) {
                return AjaxResult.error("发货单已确认发货，无需重复操作");
            }
            delivery.setDeliveryStatus(1);
            deliveryMapper.updateDeliveryStatus(delivery);

            // 2. 更新箱码的发货状态为已发货
            List<BoxCodesVO> boxCodes = deliveryMapper.selectBoxCodesByDeliveryId(delivery.getDeliveryId());
            for (BoxCodesVO boxCode : boxCodes) {
                boxCodesMapper.updateBoxCodeDeliveryStatus(boxCode.getId(), 1L);
            }
            return AjaxResult.success("发货确认成功");

        }catch (Exception e) {
            throw new RuntimeException("确认发货失败: " + e.getMessage());
        }

    }





    /**
     * 获取发货单号
     *
     * @param delivery 发货单
     * @return 发货单
     */
    @Override
    public String generateDeliveryId() {
        String dateStr = DateUtils.parseDateToStr("yyyyMMdd", new Date());
        String prefix = "DN" + dateStr;
        String maxDeliveryId = deliveryMapper.selectMaxDeliveryId(prefix);

        if (maxDeliveryId == null) {
            return prefix + "001";
        } else {
            String sequence = maxDeliveryId.substring(10);
            int nextSeq = Integer.parseInt(sequence) + 1;
            return prefix + String.format("%03d", nextSeq);
        }


    }

    /**
     * 获取页面列表数据VO
     *
     * @param delivery 发货单
     * @return 发货单
     */
    @Override
    public List<DeliveryVO> selectDeliveryVOList(Delivery delivery) {
        List<DeliveryVO> deliveryList = deliveryMapper.selectDeliveryVOList(delivery);
        // 为每个发货单加载箱码信息
        for (DeliveryVO deliveryVO : deliveryList) {
            List<BoxCodesVO> boxCodes = deliveryMapper.selectBoxCodesByDeliveryId(deliveryVO.getDeliveryId());
            deliveryVO.setBoxCodes(boxCodes);

            // 计算送货清单汇总
            deliveryVO.setDeliveryItems(calculateDeliveryItems(boxCodes));
        }
        return deliveryList;
    }

    @Override
    public DeliveryVO selectDeliveryVOById(Long id) {
        DeliveryVO deliveryVO = deliveryMapper.selectDeliveryVOById(id);

        if (deliveryVO != null) {
            List<BoxCodesVO> boxCodes = deliveryMapper.selectBoxCodesByDeliveryId(deliveryVO.getDeliveryId());
            /*  得到箱码列表  */
            deliveryVO.setBoxCodes(boxCodes);
            /*  得到发货清单  */
            deliveryVO.setDeliveryItems(calculateDeliveryItems(boxCodes));
        }
        return deliveryVO;
    }



    /**
     * 查询发货单
     * 
     * @param id 发货单主键
     * @return 发货单
     */
    @Override
    public Delivery selectDeliveryById(Long id)
    {
        return deliveryMapper.selectDeliveryById(id);
    }

    /**
     * 查询发货单列表
     * 
     * @param delivery 发货单
     * @return 发货单
     */
    @Override
    public List<Delivery> selectDeliveryList(Delivery delivery)
    {
        return deliveryMapper.selectDeliveryList(delivery);
    }

    /**
     * 新增发货单
     * 
     * @param delivery 发货单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertDelivery(Delivery delivery)
    {
        int rows = deliveryMapper.insertDelivery(delivery);
        insertDeliveryDetail(delivery);
        return rows;
    }

    /**
     * 新增发货单
     *
     * @param delivery 发货单
     * @return 结果
     */


    @Override
    @Transactional
    public int addDeliveryWithDetails(DeliveryVO deliveryVO) {
        try {
            // 1. 生成送货单号
            String deliveryId = this.generateDeliveryId();
            deliveryVO.setDeliveryId(deliveryId);

            // 2. 保存发货单主表
            Delivery delivery = new Delivery();
            BeanUtils.copyProperties(deliveryVO, delivery);
            delivery.setDeliveryStatus(0); // 待发货
//            System.out.println("发货单主表"+delivery);
            deliveryMapper.insertDelivery(delivery);

            // 3. 保存发货单明细
            if (deliveryVO.getBoxCodes() != null && !deliveryVO.getBoxCodes().isEmpty()) {
                List<DeliveryDetail> detailList = new ArrayList<>();
                for (BoxCodesVO boxCode : deliveryVO.getBoxCodes()) {
                    DeliveryDetail detail = new DeliveryDetail();
                    detail.setDeliveryId(deliveryId);
                    detail.setBoxId(boxCode.getBoxId());
                    detail.setCreatedAt(new Date());
                    detail.setUpdatedAt(new Date());
                    detailList.add(detail);
                }
                deliveryMapper.batchDeliveryDetail(detailList);
            }
            // 4. 更新箱码的发货状态
//            if (deliveryVO.getBoxCodes() != null) {
//                for (BoxCodesVO boxCode : deliveryVO.getBoxCodes()) {
//                    boxCodesMapper.updateBoxCodeDeliveryStatus(boxCode.getId(),1L);
//
//                }
//            }

            // 5. 更新采购订单详情的已送料数量
            if (deliveryVO.getDeliveryItems() != null) {
                for (DeliveryItemVO item : deliveryVO.getDeliveryItems()) {
                    purchaseOrdersMapper.updatePayoffNum(deliveryVO.getPoId(), item.getItemId(), item.getCurrentDeliveryQuantity());
                }
            }
            return 200;
        }
        catch (Exception e) {
            throw new RuntimeException("发货单创建失败: " + e.getMessage());
        }
    }


    /**
     * 修改发货单
     * 
     * @param delivery 发货单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateDelivery(Delivery delivery)
    {
        deliveryMapper.deleteDeliveryDetailByDeliveryId(delivery.getId());
        insertDeliveryDetail(delivery);
        return deliveryMapper.updateDelivery(delivery);
    }

    /**
     * 批量删除发货单
     * 
     * @param ids 需要删除的发货单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDeliveryByIds(Long[] ids)
    {
        deliveryMapper.deleteDeliveryDetailByDeliveryIds(ids);
        return deliveryMapper.deleteDeliveryByIds(ids);
    }

    /**
     * 删除发货单信息
     * 
     * @param id 发货单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDeliveryById(Long id)
    {
        deliveryMapper.deleteDeliveryDetailByDeliveryId(id);
        return deliveryMapper.deleteDeliveryById(id);
    }

    /**
     * 新增发货单明细信息
     * 
     * @param delivery 发货单对象
     */
    public void insertDeliveryDetail(Delivery delivery)
    {
        List<DeliveryDetail> deliveryDetailList = delivery.getDeliveryDetailList();
        Long id = delivery.getId();
        if (StringUtils.isNotNull(deliveryDetailList))
        {
            List<DeliveryDetail> list = new ArrayList<DeliveryDetail>();
            for (DeliveryDetail deliveryDetail : deliveryDetailList)
            {
                deliveryDetail.setDeliveryId(String.valueOf(id));
                list.add(deliveryDetail);
            }
            if (list.size() > 0)
            {
                deliveryMapper.batchDeliveryDetail(list);
            }
        }
    }

    private List<DeliveryItemVO> calculateDeliveryItems(List<BoxCodesVO> boxCodes) {
        Map<String, DeliveryItemVO> itemMap = new HashMap<>();

        for (BoxCodesVO boxCode : boxCodes) {
            String itemId = boxCode.getItemId();
            DeliveryItemVO itemVO = itemMap.get(itemId);
            PurchaseOrdersDetails purchaseOrderPageVO = purchaseOrdersMapper.selectDetailByPoIdAndItemId(boxCode.getPoId(),itemId);
            if (itemVO == null) {
                itemVO = new DeliveryItemVO();
                  itemVO.setPoNum(purchaseOrderPageVO.getPoNum());
                  itemVO.setCodeNum(purchaseOrderPageVO.getCodeNum());
                  itemVO.setItemId(itemId);
                  itemVO.setItemName(boxCode.getItemName());
                  itemVO.setBatch(boxCode.getBatch());
                  itemVO.setPoId(boxCode.getPoId());
                  itemVO.setSpec(boxCode.getSpec());
                  itemVO.setUom(boxCode.getUom());
                  itemVO.setCurrentDeliveryQuantity(0L);
                  itemVO.setBoxCount(0L);
                  itemMap.put(itemId, itemVO);
            }

            // 累加数量和箱数
            itemVO.setCurrentDeliveryQuantity(itemVO.getCurrentDeliveryQuantity() + boxCode.getBoxNum());
            itemVO.setBoxCount(itemVO.getBoxCount() + 1);
        }

        return new ArrayList<>(itemMap.values());
    }
}
